<?php

namespace App\Http\Controllers\Caiwu;

use App\Http\Controllers\Controller;
use App\Models\Contract;
use App\Models\Customer;
use App\Models\Department;
use App\Models\Finance;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;

class FinanceController extends Controller
{

    public function index(Request $request)
    {
        if ($request->ajax()){
            $user = $request->user();
            $data = $request->all([
                'customer_id',
                'num',
            ]);
            $res = Finance::query()
                ->with('customer')
                ->where(function ($q) use($user){
                    if ($user->hasPermissionTo('caiwu.finance.list_all')) {

                    } elseif ($user->hasPermissionTo('caiwu.finance.list_department_sub')) {
                        $departmentIds = Department::query()->where('parent_id',$user->department_id)->pluck('id')->toArray();
                        $departmentIds = array_merge($departmentIds,[$user->department_id]);
                        return $q->whereIn('owner_department_id', $departmentIds);
                    } elseif ($user->hasPermissionTo('caiwu.finance.list_department')) {
                        return $q->where('owner_department_id',$user->department_id);
                    }else{
                        return $q->where('owner_user_id',$user->id);
                    }
                })
                ->when($data['customer_id'], function ($query) use ($data) {
                    return $query->where('customer_id', $data['customer_id']);
                })
                ->when($data['num'], function ($query) use ($data) {
                    return $query->where('num', $data['num']);
                })
                //->where('outin','=',1)
                ->orderByDesc('id')
                ->paginate($request->get('limit', 30));
            return $this->success('ok',$res->items(),$res->total());
        }
        return View::make('caiwu.finance.index');
    }

    public function create(Request $request)
    {
        $outin = $request->input('outin');
        return View::make('caiwu.finance.create',compact('outin'));
    }

    public function store(Request $request)
    {
        $data = $request->all([
            'order_id',
            'money',
            'pay_type',
            'remark',
            'num',
            'multiple_file',
        ]);
        $order = Order::query()->where('id',$data['order_id'])->first();
        if ($order->check_status != 3){
            return $this->error('订单未审核通过');
        }
        try {
            $data = array_merge($data,[
                'num' => $order->num,
                'customer_id' => $order->customer_id,
                'owner_department_id' => $request->user()->department_id,
                'owner_user_id' => $request->user()->id,
                'owner_user_nickname' => $request->user()->nickname,
            ]);
            Finance::create($data);
            return $this->success();
        }catch (\Exception $exception){
            Log::error('添加收支记录异常：'.$exception->getMessage());
            return $this->error();
        }
    }

    public function edit($id)
    {
        $model = Finance::query()->find($id);
        return View::make('caiwu.finance.edit',compact('model'));
    }

    public function update(Request $request,$id)
    {
        $model = Finance::query()->find($id);
        if ($model->check_status==3){
            return $this->error('已审核通过，禁止修改');
        }
        $data = $request->all([
            'money',
            'pay_type',
            'remark',
            'multiple_file',
        ]);
        try {
            $model->update($data);
            return $this->success();
        }catch (\Exception $exception){
            Log::error('更新收支记录异常：'.$exception->getMessage());
            return $this->error();
        }
    }

    /**
     * 删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        $ids = $request->input('ids');
        try {
            Finance::query()->whereIn('id', $ids)->delete();
            return $this->success();
        } catch (\Exception $exception) {
            Log::error('删除收支记录异常：' . $exception->getMessage());
            return $this->error();
        }
    }

    /**
     * 审核
     * @param Request $request
     * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function check(Request $request)
    {
        $model = Finance::query()->find($request->input('id'));
        if ($request->ajax()){
            try {
                if ($model->check_status != 1){
                    return $this->error('禁止重复审核');
                }
                $data = $request->all(['check_status','check_result']);
                if ($data['check_status']==null){
                    return $this->error('请选择状态');
                }
                $data = array_merge($data,[
                    'check_time' => date('Y-m-d H:i:s'),
                    'check_user_id' => $request->user()->id,
                    'check_user_nickname' => $request->user()->nickname,
                ]);
                $model->update($data);
                // 审核通过增加付款金额
                if ($data['check_status']==3){
                    Order::query()->where('id',$model->order_id)->increment('payed_money',$model->money);
                }
                return $this->success();
            }catch (\Exception $exception){
                Log::error('收支记录审核异常：'.$exception->getMessage());
                return $this->error();
            }
        }
        return View::make('caiwu.finance.check',compact('model'));
    }

}
